import { Component, Injector, ViewChild, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AppConsts } from '@shared/AppConsts';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { EntityDtoOfInt64, BopDescServiceProxy, UserServiceProxy, BopNodeServiceProxy } from '@shared/service-proxies/service-proxies';
import { FileDownloadService } from '@shared/utils/file-download.service';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Table } from 'primeng/components/table/table';
import { CreateOrEditBopTaskModalComponent } from './create-or-edit-boptask-modal.component';
import { HttpClient } from '@angular/common/http';
import { FileUpload } from 'primeng/fileupload';
import { finalize } from 'rxjs/operators';
import { CreateOrEditBopModalComponent } from './create-or-edit-bop-modal.component';
import { Paginator } from 'primeng/components/paginator/paginator';
import { MessageService } from '@abp/message/message.service';
//查看履历
import { ShowResumeComponent } from './show-resume/show-resume.component';
import { BopExportComponent } from './bop-export/bop-export.component';
import { TskExportComponent } from './tsk-export/tsk-export.component';
import { JsUtilsApi } from 'great-jsutils';
@Component({
    templateUrl: './bop.component.html',
    encapsulation: ViewEncapsulation.None,
    styleUrls: ['./bop.component.less']
})
export class BopComponent extends AppComponentBase {
    @ViewChild('BopExportComponent') BopExportComponent: BopExportComponent;
    @ViewChild('TskExportComponent') TskExportComponent: TskExportComponent;
    @ViewChild('createOrEditBopTaskModal') createOrEditBopTaskModal: CreateOrEditBopTaskModalComponent;
    @ViewChild('createOrEditBopModal') createOrEditBopModal: CreateOrEditBopModalComponent;
    @ViewChild('dataTable') dataTable: Table;
    @ViewChild('paginator') paginator: Paginator;
    @ViewChild('ExcelFileUpload') excelFileUpload: FileUpload;
    @ViewChild('showResume') ShowResume: ShowResumeComponent;

    uploadUrl: string;
    filterText = '';
    selectedPermission = '';
    role = '';
    onlyLockedUsers = false;
    advancedFiltersAreShown = false;
    title: string; //标题
    model: string = ''
    lotNo: string = ''
    drawingNo: string = ''

    rowdata: any;//单行数据
    saveFlag = true;
    uploadedFiles = [];
    fileMd5 = undefined;
    exportInTitle = undefined;
    exportIn = false;
    fileName = undefined;
    constructor(
        injector: Injector,
        private _BopDescServiceProxy: BopDescServiceProxy,
        private _httpClient: HttpClient,
        private _messageService: MessageService,
        private _userServiceProxy: UserServiceProxy,
        private _bopNodeServiceProxy: BopNodeServiceProxy,
        private _fileDownloadService: FileDownloadService

    ) {
        super(injector);
    }
    export(row) {
        setTimeout(() => {
            this.rowdata = row;
            this.BopExportComponent.show();
        }, 10);
    }
    rangeExport(row) {
        this.message.confirm(
            '确认导出这条数据吗',
            (isConfirmed) => {
                if (isConfirmed) {
                    abp.ui.setBusy();
                    if (this.saveFlag) {
                        this.saveFlag = false;
                        this._bopNodeServiceProxy.getShootingRange(row.id).pipe(finalize(() => { }))
                            .subscribe(result => {
                                abp.ui.clearBusy();
                                this.saveFlag = true;
                                if (result.code == 0) {
                                    window.location.href = result.message;
                                } else {
                                    this._messageService.error(result.message)
                                }
                            })
                    }
                }
            }
        );
    }
    myUploader(event) {
        console.log(event);
        
        // let file = event.files[0];
        let data = { data: event.files[0], fileName: event.files[0].name };
        // JsUtilsApi.md5File(file).then(
        //     (md5) => {

        //         this.fileMd5 = md5;
        //         this.fileMd5 = this.fileMd5.toLowerCase();
        abp.ui.setBusy();
        this.saveFlag = false;
                this._bopNodeServiceProxy.shootingBigRangeBop(
                    event.files[0].name
                    // this.fileMd5
                )
                    .pipe(finalize(() => { }))
                    .subscribe(result => {
                        this.saveFlag = true;
                        abp.ui.clearBusy();
                        this.uploadedFiles = [];
                        this.fileMd5 = undefined;
                        if (result.code == 0) {
                            this._messageService.success('导入成功');
                            this.getBopList();
                        } else {
                            this._messageService.error(result.message);
                        }
                    });
            // },
            // (error) => {
            //     console.log(error);
            // }
        // );


    }
    exportTask(row) {
        setTimeout(() => {
            this.rowdata = row;
            this.TskExportComponent.show();
        }, 10);
    }
    //获取bop列表
    getBopList(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);
            return;
        }
        //this.primengTableHelper.showLoadingIndicator();
        this._BopDescServiceProxy.getBopDescList(
            this.filterText,
            this.drawingNo,
            this.model,
            this.lotNo,
            this.primengTableHelper.getSorting(this.dataTable),
            this.primengTableHelper.getMaxResultCount(this.paginator, event),
            this.primengTableHelper.getSkipCount(this.paginator, event)
        ).pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
            this.primengTableHelper.totalRecordsCount = result.totalCount;
            this.primengTableHelper.records = result.items;
            this.primengTableHelper.hideLoadingIndicator();
            if (result.totalCount == 0) {
                this._messageService.info('暂无数据！')
            }
        });
    }
    //重置搜索
    resetSearch(): void {
        this.model = ''
        this.lotNo = '',
            this.drawingNo = ''
        this.getBopList()
    }
    //bop修改
    bopEdit(row): void {
        this.rowdata = row
        this.title = '修改任务'
        setTimeout(() => {
            this.createOrEditBopTaskModal.show();
        }, 10)
    }
    //bop删除
    bopDelete(row): void {
        this.message.confirm(
            '确认删除这条数据吗',
            (isConfirmed) => {
                if (isConfirmed) {
                    if (this.saveFlag) {
                        this.saveFlag = false;
                        this._BopDescServiceProxy.deleteBopDesc(row.id).pipe(finalize(() => { }))
                            .subscribe(result => {
                                this.saveFlag = true;
                                if (result.code == 0) {
                                    this._messageService.success('删除成功！');
                                    this.getBopList();
                                } else {
                                    this._messageService.error(result.message)
                                }
                            })
                    }
                }
            }
        );
    }
    //查看履历
    lookResume(row): void {
        let that = this
        this.rowdata = row
        setTimeout(() => {
            that.ShowResume.show()
            that.ShowResume.getTableList()
        }, 20)
    }
    reloadPage(): void {
        this.paginator.changePage(this.paginator.getPage());
    }

    exportToExcel(): void {
        // this._BopDescServiceProxy.getBopListToExcel(
        //     this.filterText,
        //     this.permission ? this.selectedPermission : undefined,
        //     this.role !== '' ? parseInt(this.role) : undefined,
        //     this.onlyLockedUsers,
        //     this.primengTableHelper.getSorting(this.dataTable))
        //     .subscribe(result => {
        //         this._fileDownloadService.downloadTempFile(result);
        //     });
    }
    //创建任务
    createTask(): void {
        this.title = '新增任务'
        setTimeout(() => {
            this.createOrEditBopTaskModal.show();
        }, 10)
    }
    //打开bop树
    toBopTree(row): void {
        this.rowdata = row;
        let that = this;
        setTimeout(() => {
            that.createOrEditBopModal.show();
            that.createOrEditBopModal.getTreeInfo(false);
        }, 10);

    }
    exportPerson() {
        this.message.confirm(
            '确认要导出吗？',
            (isConfirmed) => {
                if (isConfirmed) {
                    abp.ui.setBusy();
                    this._bopNodeServiceProxy.getUserPers()
                        .subscribe(result => {
                            abp.ui.clearBusy();
                            if (result.code == 0) {
                                window.location.href = result.message;
                            } else {
                                this._messageService.error(result.message);
                            }
                        });
                }
            }
        );

    }
    //导出
    uploadExcel(data: { files: File }): void {
        // if (this.saveFlag) {
        //     this.saveFlag = false;
        const formData: FormData = new FormData();
        const file = data.files[0];
        formData.append('file', file, file.name);
        this._httpClient
            .post<any>(this.uploadUrl, formData)
            .pipe(finalize(() => this.excelFileUpload.clear()))
            .subscribe(response => {
                // if (result.code == 0) {
                this.saveFlag = true;
                if (response.success) {
                    this.notify.success(this.l('ImportUsersProcessStart'));
                } else if (response.error != null) {
                    this.notify.error(this.l('ImportUsersUploadFailed'));
                }
                // } else {
                //     this._messageService.error(result.message)
                // }

            });
        // }

    }

    onUploadExcelError(): void {
        this.notify.error(this.l('ImportUsersUploadFailed'));
    }
// 弹窗隐藏
displayclose() {
    this.fileName = undefined;
}
openDialog() {
    this.exportInTitle = '靶场BOP导入';
    this.exportIn = true;
}
alterCertificateByBusinessEv() {

    abp.ui.setBusy();
    this._bopNodeServiceProxy.shootingBigRangeBop(
        this.fileName
    )
        .pipe(finalize(() => { }))
        .subscribe(result => {
            this.saveFlag = true;
            abp.ui.clearBusy();
            this.fileName = undefined;
            if (result.code == 0) {
                this._messageService.success('导入成功');
                this.getBopList();
            } else {
                this._messageService.error(result.message);
            }
        });


}

}
